package models

import (
	"errors"
	"github.com/astaxie/beego/orm"
	_ "github.com/astaxie/beego/validation"
	"github.com/medivhzhan/weapp"
	"strings"
	"time"
)

/* table_name = user */
type User struct {
	Id                 int    `orm:"column(id);auto;pk" json:"id" description:"用户id"`
	Username           string `orm:"column(username)" json:"username" description:"用户账号"`
	Password           string `orm:"column(password)" json:"-" description:"用户密码"`
	Avatar             string `orm:"column(avatar)" json:"avatar" description:"用户头像"`
	Nickname           string `orm:"column(nickname)" json:"nickname" description:"用户昵称"`
	Telephone          string `valid:"Mobile" orm:"column(telephone)" json:"telephone" description:"用户手机号"`
	Email              string `valid:"Email" orm:"column(email)" json:"email" description:"用户邮箱"`
	Wechat             string `orm:"column(wechat)" json:"wechat" description:"用户微信号"`
	OpenId             string `orm:"column(open_id)" json:"-" description:"用户openid"`
	Qq                 string `orm:"column(qq)" json:"qq" description:"用户qq号"`
	RealName           string `json:"real_name" description:"用户真实姓名"`
	Gender             int    `json:"gender" description:"用户性别"`
	University         string `json:"university" description:"学校名称"`
	College            string `json:"college" description:"学院名"`
	Major              string `json:"major" description:"专业"`
	Grade              int    `json:"grade" description:"对应年级"`
	Province           string `json:"province" description:"用户省份"`
	City               string `json:"city" description:"用户城市"`
	Area               string `json:"area" description:"用户地区"`
	Money              int    `json:"-" description:"用户金豆数量"`
	Type               int    `json:"user_type" description:"用户类型"`
	Position           string
	Department         string
	WorkTimeStartYear  int
	WorkTimeStartMonth int
	WorkTimeEndYear    int
	WorkTimeEndMonth   int
	Education          int
	Level              string
	Hobby1             string
	Hobby2             string
	Hobby3             string
	PrimarySchool      string
	JuniorHighSchool   string
	HighSchool         string
	RealPhoto          string
	Elite              int
	Status             bool      `json:"-" description:"用户状态(0-已注销 1-有效)"`
	CreateTime         time.Time `orm:"auto_now_add;type(datetime)" json:"create_time" description:"账号创建时间"`
	//UserComment  []*UserComment `orm:"reverse(many)" json:"-" description:"用户所发表的评论"`
	// UserCompanyBrowseId []*UserCompanyBrowse `orm:"reverse(many)" json:"user_company_browse_id"`
}

/* table_name = user_comment */
type UserComment struct {
	Id             int               `orm:"column(id);auto;pk" json:"id" description:"用户评论id"`
	Type           int               `orm:"column(type)" json:"type" description:""`
	Content        string            `orm:"column(content)" json:"content"`
	Voice          string            `orm:"column(voice)"json:"voice"`
	Importance     int               `orm:"column(importance)"json:"importance"`
	Urge           int               `orm:"column(urge)"json:"urge"`
	CommentUser    *User             `orm:"column(comment_user);rel(fk)" json:"-"`
	Status         bool              `orm:"column(status)"json:"status"`
	CreateTime     time.Time         `orm:"auto_now_add;type(datetime)" json:"create_time"`
	UserCommentImg []*UserCommentImg `orm:"reverse(many)" json:"user_comment_img"`
}

/* table_name = user_comment_img */
type UserCommentImg struct {
	Id         int          `orm:"auto;pk" json:"id"`
	ImgUrl     string       `json:"img_url"`
	Comment    *UserComment `orm:"rel(fk)" json:"-"`
	Status     bool         `json:"status"`
	CreateTime time.Time    `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_company_browse */
type UserCompanyBrowse struct {
	Id         int      `orm:"auto;pk" json:"user_company_browse_id"`
	User       *User    `orm:"rel(fk)" json:"user_id"`
	Company    *Company `orm:"rel(fk)" json:"company_id"`
	Type       int
	Status     bool      `json:"company_status"`
	CreateTime time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_resume_put */
type UserResumePut struct {
	Id         int         `orm:"auto;pk"`
	Resume     *UserResume `orm:"rel(fk)"`
	Result     int         `json:"result"`
	ResultType int
	Note       string
	Company    *Company    `orm:"rel(fk)"`
	Job        *CompanyJob `orm:"rel(fk)"`
	User       *User       `orm:"rel(fk)" json:"-"`
	Status     bool
	CreateTime time.Time `orm:"auto_now_add;type(datetime)"`
}

/* table_name = user_star_company */
type UserStarCompany struct {
	Id         int       `orm:"auto;pk"`
	Company    *Company  `orm:"rel(fk)"`
	User       *User     `orm:"rel(fk)" json:"-"`
	Status     bool      `json:"status"`
	CreateTime time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_star */
type UserStar struct {
	Id         int       `orm:"auto;pk" json:"id"`
	StarUser   *User     `orm:"rel(fk)" json:"star_user"`
	User       *User     `orm:"rel(fk)" json:"-"`
	Status     bool      `json:"status"`
	CreateTime time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_invite */
type UserInvite struct {
	Id            int       `orm:"auto;pk" json:"user_invite_id"`
	InvitedUserId *User     `orm:"rel(fk)" json:"invited_user_id"`
	InviteUserId  *User     `orm:"rel(fk)" json:"invite_user_id"`
	Status        bool      `json:"status"`
	CreateTime    time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_identity */
type UserIdentity struct {
	Id         int   `orm:"auto;pk"`
	User       *User `orm:"rel(fk)"`
	IdentityId int
	Status     bool      `json:"status"`
	CreateTime time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_label */
type UserLabel struct {
	Id         int `orm:"auto;pk"`
	Label      string
	User       *User `orm:"rel(fk)" json:"-"`
	Type       int
	Status     bool          `orm:"default(true)" json:"status"`
	CreateTime time.Time     `orm:"auto_now_add;type(datetime)" json:"create_time"`
	UserPraise []*UserPraise `orm:"reverse(many)" json:"praise"`
}

/* table_name = user_praise */
type UserPraise struct {
	Id         int        `orm:"auto;pk"`
	UserLabel  *UserLabel `orm:"rel(fk)"`
	PraiseUser *User      `orm:"rel(fk)" json:"-"`
	Status     bool       `json:"status"`
	CreateTime time.Time  `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_honor */
type UserHonor struct {
	Id           int `orm:"auto;pk"`
	Description  string
	Img          string
	Type         int
	Level        string
	User         *User `orm:"rel(fk)" json:"-"`
	GetTimeYear  int
	GetTimeMonth int
	Status       bool      `json:"status" orm:"default(true)"`
	CreateTime   time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_resume */
type UserResume struct {
	Id                              int `orm:"auto;pk"`
	Name                            string
	Gender                          bool
	PoliticalStatus                 int
	Birth                           time.Time `orm:"type(datetime)"`
	Phone                           string
	Email                           string
	Province                        string
	City                            string
	Area                            string
	Nationality                     string
	Height                          float64
	Weight                          float64
	Education                       int
	EducationType                   bool
	SchoolName                      string
	SchoolNationality               string
	SchoolType                      int
	Faculty                         string
	Major                           string
	Minor                           string
	SchoolStart                     int
	SchoolEnd                       int
	SecondEducation                 string
	ForeignLanguage                 string
	ForeignLanguageLevel            string
	OtherForeignLanguageInformation string
	Computer                        int
	OtherComputerInformation        string
	Position                        string
	Department                      string
	WorkingTimeStartYear            int
	WorkingTimeEndYear              int
	WorkingTimeStartMonth           int
	WorkingTimeEndMonth             int
	SelfEvaluation                  string
	TargetJob                       string
	TargetSalary                    int
	TargetCity                      string
	SocialPractices                 []*SocialPractice `orm:"reverse(many)"`
	User                            *User             `orm:"rel(fk)" json:"-"`
	Status                          bool              `json:"status" orm:"default(true)"`
	CreateTime                      time.Time         `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_info */
type UserInfo struct {
	Id               int `orm:"auto;pk"`
	HighSchool       string
	JuniorHighSchool string
	PrimarySchool    string
	User             *User     `orm:"rel(fk)"`
	Status           bool      `json:"status" orm:"default(true)"`
	CreateTime       time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_entrepreneurial_elite */
type UserEntrepreneurialElite struct {
	Id          int `orm:"auto;pk"`
	IdCardFront string
	IdCardBack  string
	Education   int
	Grade       int
	Gender      int
	City        string
	User        *User     `orm:"rel(fk)"`
	Status      bool      `json:"status" orm:"default(true)"`
	CreateTime  time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_self_introduction */
type UserSelfIntroduction struct {
	Id         int `orm:"auto;pk"`
	Video      string
	Type       int
	User       *User     `orm:"rel(fk)" json:"-"`
	Status     bool      `json:"status" orm:"default(true)"`
	CreateTime time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = social_practice */
type SocialPractice struct {
	Id         int `orm:"auto;pk"`
	Year       int
	Month      int
	Day        int
	Content    string
	UserResume *UserResume `orm:"rel(fk)" json:"-"`
	Status     bool        `json:"status" orm:"default(true)"`
	CreateTime time.Time   `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

/* table_name = user_put_and_company_invite*/
type UserPutAndCompanyInvite struct {
	Id            int         `orm:"auto;pk"`
	Resume        *UserResume `orm:"rel(fk)"`
	Company       *Company    `orm:"rel(fk)"`
	Job           *CompanyJob `orm:"rel(fk)"`
	User          *User       `orm:"rel(fk)" json:"-"`
	Note          string
	CompanyAnswer int
	UserAnswer    int
	IsPut         bool
	Offer         int
	Status        bool      `json:"status" orm:"default(true)"`
	CreateTime    time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"`
}

// Own data structure
type Label struct {
	Character []string
	Ability   []string
	Specialty []string
}

type University struct {
	ProvinceName string
	Cities       []City
}

type City struct {
	CityName     string
	Universities []string
}

type MyLabel struct {
	Id        int    `json:"id"`
	Label     string `json:"label"`
	PraiseNum int    `json:"praiseNum"`
	Type      int    `json:"type"`
	Praised   bool   `json:"praised"`
}

type SecondJob struct {
	Name string
	Next []ThirdJob
}

type ThirdJob struct {
	Name string
	Next []string
}

type PutAndInviteWithStar struct {
	PutAndInvite UserPutAndCompanyInvite
	Star         bool
}

const (
	APPId     = "wx78ed10e1da8596d6"
	AppSecret = "90bbbe41c57ef867d8a4912dfb42cdb4"

	PrimarySchool    = 1
	JuniorHighSchool = 2
	HighSchool       = 3

	// 院校登记 Enum
	Specialist    = 1
	Undergraduate = 2
	Master        = 3
	Doctor        = 4
	Postdoc       = 5

	// 奖项 Enum
	Scholarship              = 0
	CertificateOfAppointment = 1
	CompetitionAwards        = 2
	Patent                   = 3
	OtherCertificates        = 4
)

/*
用户注册
*/
func Register(user *User) (int, error) {
	user.Status = true
	userId, err := O.Insert(user)

	userResume := UserResume{Id: int(userId), User: &User{Id: int(userId)}}
	_, err = O.Insert(&userResume)

	return int(userId), err
}

/*
用户被邀请 注册
*/
func RegisterByInvited(user *User, invite UserInvite) (int, error) {
	_, err := O.Insert(&invite)
	if err != nil {
		return 0, err
	}
	userId, err := O.Insert(user)

	userResume := UserResume{Id: int(userId), User: &User{Id: int(userId)}}
	_, err = O.Insert(&userResume)

	return int(userId), err
}

/*
用户登录: 用户名 -> 手机号 -> 邮箱
*/
func Login(user User) (userId int, err error) {
	user.Status = true
	err = O.Read(&user, "username", "password", "status")
	if err != nil {
		user.Telephone = user.Username
		err = O.Read(&user, "telephone", "password", "status")
		if err != nil {
			user.Email = user.Username
			err = O.Read(&user, "email", "password", "status")
		}
	}
	if err != nil {
		err = errors.New("LoginFailed")
	}

	return user.Id, err
}

/*
微信小程序登录
*/
func WxLogin(code string) (map[string]interface{}, error) {
	var user User
	res, err := weapp.Login(APPId, AppSecret, code)
	if err != nil {
		return nil, errors.New("SystemFailed")
	}

	err = O.QueryTable("user").
		Filter("open_id", res.OpenID).
		One(&user)
	if err != nil {
		user.OpenId = res.OpenID
		user.Wechat = res.UnionID
		_, err = Register(&user)
		if err != nil {
			return nil, errors.New("LoginFailed")
		}
	}

	data := make(map[string]interface{})
	data["user_id"] = user.Id
	data["open_id"] = res.OpenID
	data["session_key"] = res.SessionKey
	data["union_id"] = res.UnionID

	return data, err
}

/*
查询用户 通过用户 id
*/
func QueryUserById(id int) (*User, error) {
	user := User{Id: id, Status: true}
	err := O.Read(&user)

	if err != nil {
		err = errors.New("UserNotExist")
	}
	return &user, err
}

/*
查询用户 通过用户 id
*/
func QueryUserByUsername(username string) (*User, error) {
	user := User{Username: username, Status: true}
	err := O.Read(&user)

	return &user, err
}

/*
用户更新信息
*/
func UpdateUserInfo(user User) (err error) {
	dbUser, err := QueryUserById(user.Id)
	myUser := mergeUser(user, dbUser)

	_, err = O.Update(&myUser,
		"Nickname",
		"RealName",
		"Gender",
		"University",
		"College",
		"Major",
		"Grade",
		"Avatar",
		"Province",
		"City",
		"Area",
		"Department",
		"Position",
	)
	return err
}

/*
用户更新一寸照
*/
func UpdateUserRealPhoto(user User) (err error) {
	_, err = O.Update(&user,
		"RealPhoto",
	)
	return err
}

/*
更换手机号
*/
func ChangeTelephone(user User) (err error) {
	_, err = O.Update(&user,
		"Telephone")

	return err
}

/*
修改密码
*/
func ChangePassword(user User) (err error) {
	_, err = O.Update(&user,
		"Password")

	return err
}

/*
修改邮箱
*/
func ChangeEmail(user User) (err error) {
	_, err = O.Update(&user,
		"Email")

	return err
}

/*
谁看了我
*/
func QueryBrowsedHistoryByUserId(id int, keyword string, page int, limit int) ([]*UserCompanyBrowse, error) {
	var userBrowse []*UserCompanyBrowse

	qs := O.
		QueryTable("user_company_browse").
		Filter("status", 1).Filter("user_id", id).Filter("type", 1)
	if keyword != "" {
		qs = getUserByKeyword(qs, keyword)
	}
	_, err := qs.
		Limit(limit, page).
		All(&userBrowse)

	for _, browse := range userBrowse {
		browse.Company, err = GetCompanyById(browse.Company.Id)
		browse.Company.Job, err = GetCompanyJobByCompanyId(browse.Company.Id)
	}
	return userBrowse, err
}

/*
我的浏览
*/
func QueryBrowseHistoryByUserId(id int, keyword string, page int, limit int) ([]*UserCompanyBrowse, error) {
	var userBrowse []*UserCompanyBrowse
	qs := O.
		QueryTable("user_company_browse").
		Filter("status", 1).Filter("user_id", id).Filter("type", 0)
	if keyword != "" {
		qs = getUserByKeyword(qs, keyword)
	}
	_, err := qs.
		Limit(limit, page).
		All(&userBrowse)

	for _, browse := range userBrowse {
		browse.Company, err = GetCompanyById(browse.Company.Id)
		browse.Company.Job, err = GetCompanyJobByCompanyId(browse.Company.Id)
	}
	return userBrowse, err
}

/*
查看已投简历
*/
func QueryPutResumeById(id int, page int, limit int) ([]*UserResumePut, error) {
	var userResumePuts []*UserResumePut
	_, err := O.QueryTable("user_resume_put").
		Filter("status", 1).Filter("user_id", id).Limit(limit, page).
		All(&userResumePuts)

	//data := getInfoFromResumePut(userResumePuts)
	for _, userResumePut := range userResumePuts {
		userResumePut.Company, err = GetCompanyById(userResumePut.Company.Id)
		userResumePut.Job, err = GetCompanyJobById(userResumePut.Job.Id)
	}
	return userResumePuts, err
}

/*
查看已投简历(指定结果)
*/
func QueryPutResumeByResult(userId int, result int, page int, limit int) ([]*UserResumePut, error) {
	var userResumePuts []*UserResumePut
	_, err := O.QueryTable("user_resume_put").
		Filter("status", 1).Filter("user_id", userId).Filter("result", result).
		Limit(limit, page).
		All(&userResumePuts)

	for _, userResumePut := range userResumePuts {
		userResumePut.Company, err = GetCompanyById(userResumePut.Company.Id)
		userResumePut.Job, err = GetCompanyJobById(userResumePut.Job.Id)
	}
	return userResumePuts, err
}

/*
查看已投简历(指定公司)
*/
func QueryPutResumeByCompany(userId int, companyId int, page int, limit int) ([]*UserResumePut, error) {
	var userResumePuts []*UserResumePut
	_, err := O.QueryTable("user_resume_put").
		Filter("status", 1).Filter("user_id", userId).Filter("company_id", companyId).
		Limit(limit, page).
		All(&userResumePuts)

	for _, userResumePut := range userResumePuts {
		userResumePut.Company, err = GetCompanyById(userResumePut.Company.Id)
		userResumePut.Job, err = GetCompanyJobById(userResumePut.Job.Id)
	}
	return userResumePuts, err
}

/*
投放简历(已检验简历是否属于本人)
*/
func PutResume(resumePut UserResumePut) (int, error) {
	resume, err := QueryResumeByResumeId(resumePut.Resume.Id)
	if err != nil {
		return 0, err
	}
	resume.User = resumePut.User
	result, err := checkResumeBelongUser(resume)
	if result {
		resumePut.Status = true
		resumePut.Result = 0
		resumePut.ResultType = 2
		resumeId, err := O.Insert(&resumePut)
		return int(resumeId), err
	}
	return 0, err
}

/*
更新已投简历状态
*/
func UpdateResumePut(resumePut UserResumePut) error {
	var dbResumePut UserResumePut
	_ = O.QueryTable("user_resume_put").
		Filter("id", resumePut.Id).
		One(&dbResumePut)
	// 公司同意用户简历 - 简历进入下一轮
	if resumePut.ResultType == 1 && resumePut.Result != 4 {
		resumePut.Result = dbResumePut.Result + 1
		resumePut.ResultType = 2
	}
	_, err := O.Update(&resumePut,
		"result",
		"result_type")

	return err
}

/*
 更新坐等offer状态
*/
func UpdateCompanyInvite(interview CompanyInterview) error {
	var interviews []*CompanyInterview
	// 检查 是否有已同意且未违约 的记录
	_, err := O.QueryTable("company_interview").
		Filter("status", 1).Filter("user_id", interview.User.Id).Filter("result_type", 1).Filter("is_payed", 0).
		All(&interviews)
	if err == nil && len(interviews) > 0 {
		return errors.New("AlreadyAccept")
	}
	if interview.ResultType != 1 && interview.ResultType != 2 {
		return errors.New("IllegalParam")
	}

	interview.Result = interview.Result + 1
	_, err = O.Update(&interview,
		"result_type",
		"result")
	if err != nil {
		err = errors.New("UpdateDataFail")
	}
	return err
}

/*
关注用户
*/
func AddStar(star *UserStar) (int, error) {
	star.Status = true
	starId, err := O.Insert(star)

	return int(starId), err
}

/*
查看我的关注
*/
func QueryMyStar(userId int, page int, limit int, keyword string) ([]*User, error) {
	var userStars []*UserStar
	var returnUserStars []*UserStar
	var err error

	if keyword != "" {
		_, err = O.QueryTable("user_star").
			Filter("status", 1).Filter("user_id", userId).
			All(&userStars)
		for _, userStar := range userStars {
			user, err := QueryUserById(userStar.StarUser.Id)
			if err != nil {
				return nil, errors.New("UserNotExist")
			}
			if searchForUserByKeyword(user, keyword) {
				returnUserStars = append(returnUserStars, userStar)
			}
		}
		returnUserStars, err = checkPageAndLimitOfUserStar(returnUserStars, page, limit)
	} else {
		_, err = O.QueryTable("user_star").
			Filter("status", 1).Filter("user_id", userId).
			Limit(limit, page).
			All(&returnUserStars)
	}

	if err != nil {
		return nil, err
	}
	users, err := getStarUserFromUserStar(returnUserStars)
	return users, err
}

/*
取消关注
*/
func DeleteMyStar(userStar *UserStar) error {
	_, err := O.Delete(userStar)

	return err
}

/*
查看关注我的
*/
func QueryStarMe(userId int, page int, limit int, keyword string) ([]*User, error) {
	var userStars []*UserStar
	var returnUserStars []*UserStar
	var err error

	if keyword != "" {
		_, err = O.QueryTable("user_star").
			Filter("status", 1).Filter("star_user_id", userId).
			All(&userStars)
		for _, userStar := range userStars {
			user, err := QueryUserById(userStar.User.Id)
			if err != nil {
				return nil, errors.New("UserNotExist")
			}
			if searchForUserByKeyword(user, keyword) {
				returnUserStars = append(returnUserStars, userStar)
			}
		}
		returnUserStars, err = checkPageAndLimitOfUserStar(returnUserStars, page, limit)
	} else {
		_, err = O.QueryTable("user_star").
			Filter("status", 1).Filter("star_user_id", userId).
			Limit(limit, page).
			All(&returnUserStars)
	}

	if err != nil {
		return nil, err
	}
	users, err := getUserFromUserStar(returnUserStars)
	return users, err
}

/*
查看互相关注
*/
func QueryBiStar(userId int, page int, limit int, keyword string) ([]*User, error) {
	var usersStarMe []*UserStar
	var users []*UserStar
	var user UserStar
	var returnUserStar []*UserStar

	_, err := O.QueryTable("user_star").
		Filter("status", 1).Filter("star_user_id", userId).
		All(&usersStarMe)

	for _, u := range usersStarMe {
		err = O.QueryTable("user_star").
			Filter("status", 1).Filter("star_user_id", u.User.Id).Filter("user_id", userId).
			One(&user)
		if err != nil {
			continue
		}
		users = append(users, &user)
	}

	if keyword != "" {
		for _, userStar := range users {
			d, err := QueryUserById(userStar.User.Id)
			if err != nil {
				return nil, errors.New("UserNotExist")
			}
			if searchForUserByKeyword(d, keyword) {
				returnUserStar = append(returnUserStar, userStar)
			}
		}
		returnUserStar, err = checkPageAndLimitOfUserStar(returnUserStar, page, limit)
		return getStarUserFromUserStar(returnUserStar)
	} else {
		if len(users) < page+limit {
			users = users[page:]
		} else {
			users = users[page : page+limit]
		}
		data, err := getStarUserFromUserStar(users)
		return data, err
	}
}

/*
发表评论/提出建议/投诉
*/
func AddComment(comment *UserComment) error {
	comment.Status = true
	_, err := O.Insert(comment)

	return err
}

/*
删除评论/建议/投诉
*/
func DeleteComment(comment *UserComment) error {
	result, err := checkCommentBelongUser(comment)
	if result == false {
		return err
	}
	comment.Status = false
	_, err = O.Update(comment,
		"status")

	return err
}

/*
获取所有评论(需权限管理)
*/

/*
获取自己提出的建议/投诉/评论
*/
func QueryCommentById(userId int, page int, limit int) ([]*UserComment, error) {
	var userComments []*UserComment
	_, err := O.QueryTable("user_comment").
		Filter("status", 1).Filter("comment_user", userId).
		Limit(limit, page).
		All(&userComments)

	return userComments, err
}

/*
获取自己提出的建议/投诉/评论
*/
func QueryAllCommentById(userId int, page int, limit int) ([]*UserComment, error) {
	var userComments []*UserComment
	result, err := checkUserAsManager(userId)
	if !result {
		return nil, err
	}
	_, err = O.QueryTable("user_comment").
		Filter("status", 1).
		Limit(limit, page).
		All(&userComments)

	return userComments, err
}

/*
获取其他 考研族，外国籍留学生，中国籍留学生，创业精英
*/
func QueryByIdentity(identityId int, userId int, page int, limit int) ([]*User, error) {
	var userIdentities []*UserIdentity

	_, err := O.QueryTable("user_identity").
		Filter("status", 1).Filter("identity_id", identityId).Exclude("user_id", userId).
		Limit(limit, page).
		All(&userIdentities)

	user, err := getUserFromUserIdentity(userIdentities)

	return user, err
}

/*
成为 考研族，外国籍留学生，中国籍留学生，创业精英
*/
func InsertIdentity(identity *UserIdentity) (int, error) {
	identity.Status = true
	_, err := O.Insert(identity)

	return identity.Id, err
}

/*
退出 考研族，外国籍留学生，中国籍留学生，创业精英
*/
func ExitIdentity(identity *UserIdentity) error {
	_, err := O.Delete(identity)

	return err
}

/*
添加 用户标签(重复标签不可添加)
*/
func AddLabel(label *UserLabel) error {
	label.Status = true
	result := checkLabelExist(label)
	if result {
		return errors.New("ContentAlreadyExist")
	}
	_, err := O.Insert(label)
	if err != nil {
		err = errors.New("AddDataFail")
	}

	return err
}

/*
删除 用户标签
*/
func DeleteLabel(label *UserLabel) error {
	result, err := checkLabelBelongUser(label)
	if result == false {
		return err
	}

	_, err = O.Delete(label)
	return err
}

/*
查询用户标签
*/
func QueryUserLabel(userId int) ([]MyLabel, error) {
	var userLabels []*UserLabel
	var labels []MyLabel

	_, err := O.QueryTable("user_label").
		Filter("status", 1).Filter("user_id", userId).
		All(&userLabels)

	for i := 0; i < len(userLabels); i++ {
		var label MyLabel
		userLabel := userLabels[i]
		label.Id = userLabel.Id
		label.Label = userLabel.Label
		label.PraiseNum, err = getPraiseNum(userLabel)
		label.Type = userLabel.Type

		labels = append(labels, label)
	}

	return labels, err
}

/*
查询用户标签
*/
func QueryOtherLabel(id int, userId int) ([]MyLabel, error) {
	var userLabels []*UserLabel
	var userPraise UserPraise
	var labels []MyLabel

	_, err := O.QueryTable("user_label").
		Filter("status", 1).Filter("user_id", id).
		All(&userLabels)

	for i := 0; i < len(userLabels); i++ {
		userLabel := userLabels[i]
		var label MyLabel
		err := O.QueryTable("user_praise").
			Filter("user_label_id", userLabel.Id).Filter("praise_user_id", userId).
			One(&userPraise)
		if err != nil || userPraise == *new(UserPraise) {
			label.Praised = false
		} else {
			label.Praised = true
		}
		label.Id = userLabel.Id
		label.Label = userLabel.Label
		label.PraiseNum, err = getPraiseNum(userLabel)
		label.Type = userLabel.Type

		labels = append(labels, label)
	}

	return labels, err
}

/*
查询单个标签
*/
func QueryLabel(labelId int) (*UserLabel, error) {

	userLabel := UserLabel{Id: labelId, Status: true}
	err := O.Read(&userLabel)

	return &userLabel, err
}

/*
赞 用户指定标签
*/
func PraiseLabel(praise *UserPraise) error {
	praise.Status = true
	_, err := O.Insert(praise)

	return err
}

/*
取消 赞
*/
func CancelPraise(praise UserPraise) error {
	var dbPraise UserPraise
	_ = O.QueryTable("user_praise").
		Filter("status", 1).Filter("user_label_id", praise.UserLabel.Id).Filter("praise_user_id", praise.PraiseUser.Id).
		One(&dbPraise)
	if dbPraise.Id == 0 {
		return errors.New("LabelNotExist")
	}
	_, err := O.Delete(&dbPraise)

	return err
}

/*
添加荣誉
*/
func AddHonor(honor *UserHonor) (int, error) {
	honor.Status = true
	_, err := O.Insert(honor)

	return honor.Id, err
}

/*
删除荣誉
*/
func DeleteHonor(honor *UserHonor) error {
	print(honor.Id)
	_, err := O.Delete(honor)

	return err
}

/*
修改荣誉
*/
func UpdateHonor(honor *UserHonor) error {
	_, err := O.Update(honor,
		"description",
		"img",
		"get_time_year",
		"get_time_month",
		"level",
		"type",
	)

	return err
}

/*
查询用户所有荣誉
*/
func QueryUserHonor(userId int, page int, limit int) ([]*UserHonor, error) {
	var userHonors []*UserHonor

	_, err := O.QueryTable("user_honor").
		Filter("status", 1).Filter("user_id", userId).
		Limit(limit, page).
		All(&userHonors)

	return userHonors, err
}

/*
查询指定荣誉
*/
func QueryHonor(honorId int) (UserHonor, error) {
	var userHonor UserHonor

	err := O.QueryTable("user_honor").
		Filter("status", 1).Filter("id", honorId).
		One(&userHonor)

	return userHonor, err
}

/*
添加简历
*/
func AddResume(resume *UserResume) (int, error) {
	resume.Status = true
	_, err := O.Insert(resume)

	return resume.Id, err
}

/*
查看指定id简历
*/
func QueryResumeByResumeId(resumeId int) (*UserResume, error) {
	var userResume UserResume

	err := O.QueryTable("user_resume").
		Filter("status", 1).Filter("id", resumeId).
		One(&userResume)
	_, err = O.QueryTable("social_practice").
		Filter("status", 1).Filter("user_resume_id", resumeId).
		All(&userResume.SocialPractices)

	return &userResume, err
}

/*
查看简历列表
*/
func QueryResumeByUserId(userId int) (UserResume, error) {
	var userResume UserResume

	err := O.QueryTable("user_resume").
		Filter("status", 1).Filter("user_id", userId).
		One(&userResume)

	return userResume, err
}

/*
更新简历
*/
func UpdateResume(resume *UserResume) error {
	_, err := O.Update(resume)

	return err
}

/*
查看相同地区人(老乡)
*/
func QueryFellow(userId int, page int, limit int) ([]*User, error) {
	var users []*User
	user, err := QueryUserById(userId)
	if err != nil {
		return nil, errors.New("UserNotExist")
	}
	if user.Province == "" || user.City == "" {
		return nil, errors.New("IncompleteInformation")
	}

	_, err = O.QueryTable("user").
		Filter("status", 1).Filter("province", user.Province).Filter("city", user.City).
		Exclude("id", userId).
		Limit(limit, page).
		All(&users)
	if err != nil {
		err = errors.New("GetDataFail")
	}

	return users, err
}

/*
申请成为创业精英
*/
func BecomeEntrepreneurialElite(elite *UserEntrepreneurialElite) (int, error) {
	elite.Status = false
	id, err := O.Insert(elite)

	return int(id), err
}

/*
 记录浏览记录
*/
func AddBrowseCompany(browse *UserCompanyBrowse) error {
	browse.Status = true
	print(browse)
	_, err := O.Insert(browse)

	return err
}

/*
 用户查看公司邀请
*/
func QueryCompanyInviteByUserId(userId int, page int, limit int) ([]*CompanyInterview, error) {
	var companyInterviews []*CompanyInterview

	_, err := O.QueryTable("company_interview").
		Filter("status", 1).Filter("user_id", userId).
		Limit(limit, page).
		All(&companyInterviews)
	if err != nil {
		err = errors.New("GetDataFail")
	}

	companyInterviews, err = getCompanyAndJobFromCompanyInterview(companyInterviews)

	return companyInterviews, err
}

/*
 查询用户自我介绍
*/
func QuerySelfIntroduction(userId int, t int) (*UserSelfIntroduction, error) {
	var userSelfIntroductions []*UserSelfIntroduction

	_, err := O.QueryTable("user_self_introduction").
		Filter("status", 1).Filter("user_id", userId).Filter("type", t).
		OrderBy("create_time").
		All(&userSelfIntroductions)

	if len(userSelfIntroductions) != 0 {
		return userSelfIntroductions[len(userSelfIntroductions)-1], err
	} else {
		return nil, errors.New("IncompleteInformation")
	}
}

/*
 上传用户自我介绍
*/
func AddSelfIntroduction(introduction UserSelfIntroduction) (int, error) {
	introduction.Status = true

	introductionId, err := O.Insert(&introduction)

	return int(introductionId), err
}

/*
更新用户学校信息
*/
func UpdateUserSchool(user User) error {
	_, err := O.Update(&user,
		"junior_high_school",
		"high_school",
		"primary_school",
	)

	return err
}

/*
更新用户职务信息
*/
func UpdateUserPosition(user User) error {
	_, err := O.Update(&user,
		"position",
		"work_time_start_year",
		"work_time_start_month",
		"work_time_end_year",
		"work_time_end_month",
		"level",
		"department",
	)

	return err
}

/*
更新用户兴趣爱好信息
*/
func UpdateUserHobby(user User) error {
	_, err := O.Update(&user,
		"hobby1",
		"hobby2",
		"hobby3",
	)

	return err
}

/*
更新用户区域信息
*/
func UpdateUserArea(user User) error {
	_, err := O.Update(&user,
		"province",
		"city",
		"area",
	)

	return err
}

/*
筛选学生学校
*/
func FilterUserSchool(userId int, keyword string, city string, gender int, t int, page int, limit int) ([]*User, error) {
	var users []*User
	var user User
	err := O.QueryTable("user").Filter("id", userId).One(&user)
	qs := O.QueryTable("user")

	if city != "" {
		qs = qs.Filter("city", city)
	}
	if gender != -1 {
		qs = qs.Filter("gender", gender)
	}
	if t != -1 {
		if t == 1 {
			qs = qs.Filter("primary_school", user.PrimarySchool)
		} else if t == 2 {
			qs = qs.Filter("junior_high_school", user.JuniorHighSchool)
		} else if t == 3 {
			qs = qs.Filter("high_school", user.HighSchool)
		}
	}
	if keyword != "" {
		qs = getUserByKeyword(qs, keyword)
	}

	_, err = qs.
		Exclude("id", userId).
		Filter("status", 1).
		Limit(limit, page).
		All(&users)

	return users, err
}

/*
筛选学生干部
*/
func FilterStudentLeaders(userId int, keyword string, position int, department string, level int, gender int, page int, limit int) ([]*User, error) {
	var users []*User
	qs := O.QueryTable("user")

	var PositionList = [4][2]string{{"干事", "errorPosition"}, {"部长", "副部长"}, {"会长", "副会长"}, {"主席", "副主席"}}
	if position != -1 {
		qs = qs.Filter("position__in", PositionList[position])
	}
	if department != "" {
		qs = qs.Filter("department", department)
	}
	if level != -1 {
		qs = qs.Filter("level", level)
	}
	if gender != -1 {
		qs = qs.Filter("gender", gender)
	}
	if keyword != "" {
		qs = getUserByKeyword(qs, keyword)
	}

	_, err := qs.
		Exclude("id", userId).
		Filter("status", 1).
		Limit(limit, page).
		All(&users)

	return users, err
}

/*
筛选兴趣爱好
*/
func FilterHobby(userId int, keyword string, hobby string, education int, grade int, gender int, page int, limit int) ([]*User, error) {
	var users []*User
	qs := O.QueryTable("user")
	if education != -1 {
		qs = qs.Filter("education", education)
	}
	if grade != -1 {
		qs = qs.Filter("grade", grade)
	}
	if gender != -1 {
		qs = qs.Filter("gender", gender)
	}

	if hobby != "" {
		cond := orm.NewCondition().
			Or("hobby1__icontains", hobby).
			Or("hobby2__icontains", hobby).
			Or("hobby3__icontains", hobby)
		qs = qs.SetCond(cond)
	}
	if keyword != "" {
		qs = getUserByKeyword(qs, keyword)
	}
	_, err := qs.
		Exclude("id", userId).
		Filter("status", 1).
		Limit(limit, page).
		All(&users)

	return users, err
}

/*
 筛选老乡列表
*/
func FilterFellow(userId int, keyword string, education int, grade int, gender int, page int, limit int) ([]*User, error) {
	var users []*User

	user, err := QueryUserById(userId)
	if err != nil {
		return nil, errors.New("UserNotExist")
	}
	if user.Province == "" || user.City == "" {
		return nil, errors.New("IncompleteInformation")
	}
	qs := O.QueryTable("user").
		Filter("province", user.Province).Filter("city", user.City)

	if education != -1 {
		qs = qs.Filter("education", education)
	}
	if grade != -1 {
		qs = qs.Filter("grade", grade)
	}
	if gender != -1 {
		qs = qs.Filter("gender", gender)
	}
	if keyword != "" {
		qs = getUserByKeyword(qs, keyword)
	}

	_, err = qs.
		Exclude("id", userId).
		Filter("status", 1).
		Limit(limit, page).
		All(&users)
	if err != nil {
		err = errors.New("ContentIsNull")
	}

	return users, err
}

func ImportUser(users []User) (int, error) {
	successNum, err := O.InsertMulti(len(users), users)
	if err != nil {
		err = errors.New("ImportFailed")
	}
	return int(successNum), err
}

/*
 用户关注公司
*/
func StarCompany(userStarCompany *UserStarCompany) (int, error) {
	userStarCompany.Status = true
	id, err := O.Insert(userStarCompany)

	return int(id), err
}

/*
 查询用户关注的所有公司
*/
func QueryAllStarCompanies(userId int, page int, limit int) ([]CompanyStar, error) {
	var userStarCompanies []*UserStarCompany
	var companyStars []CompanyStar

	_, err := O.QueryTable("user_star_company").
		Filter("status", 1).Filter("user_id", userId).Limit(limit, page).
		All(&userStarCompanies)
	for _, userStarCompany := range userStarCompanies {
		err = O.QueryTable("company").
			Filter("status", 1).Filter("id", userStarCompany.Company.Id).
			One(userStarCompany.Company)
	}

	for _, userStarCompany := range userStarCompanies {
		userStarCompany.Company.Job, err = GetCompanyJobByCompanyId(userStarCompany.Company.Id)
		userStarCompany.Company.Live, err = GetLiveByCompanyId(userStarCompany.Company.Id)

		companyStar := CompanyStar{
			Company: userStarCompany.Company,
			IsStar:  true,
		}
		companyStars = append(companyStars, companyStar)
	}

	return companyStars, err
}

/*
 取消关注的公司
*/
func CancelStarCompany(userStarCompany UserStarCompany) error {
	err := O.QueryTable("user_star_company").
		Filter("user_id", userStarCompany.User.Id).Filter("company_id", userStarCompany.Company.Id).Filter("status", 1).
		One(&userStarCompany)

	_, err = O.Delete(&userStarCompany)

	return err
}

/*
 计算用户精英值
*/
func UpdateUserElite(userId int) error {
	user, err := QueryUserById(userId)
	if err != nil {
		return errors.New("UserNotExist")
	}
	userResume, err := QueryResumeByUserId(userId)
	if err != nil {
		return errors.New("UserResumeNotExist")
	}
	userHonors, err := getAllHonor(userId)
	elite := 0

	// 计算 底分(学校的分数)
	eduction := userResume.Education
	schoolType := userResume.SchoolType
	if eduction == Specialist {
		elite += 100
	} else if eduction == Undergraduate {
		elite += 200
		if schoolType == 0 { // 985 高校
			elite += 20
		} else if schoolType == 1 { // 211 高校
			elite += 10
		}
	} else if eduction == Master {
		elite += 300
	} else if eduction == Doctor {
		elite += 400
	} else if eduction == Postdoc {
		elite += 500
	}
	// 计算 辅修专业 (只考虑了一个辅修专业...)
	minor := userResume.Minor
	if minor != "" {
		elite += 60
	}
	// 计算 英语
	foreignLanguageLevel := userResume.ForeignLanguageLevel
	if !strings.Contains(userResume.Major, "英语") { // 非英语专业
		if foreignLanguageLevel == "英语六级" && eduction == Undergraduate { // 本科-六级
			elite += 20
		} else if foreignLanguageLevel == "英语六级" && eduction == Specialist { // 专科-六级
			elite += 25
		} else if foreignLanguageLevel == "英语四级" && eduction == Specialist { // 专科-四级
			elite += 15
		}
	}
	// 计算 计算机
	computer := userResume.Computer
	if computer >= 3 && !strings.Contains(userResume.Major, "计算机") {
		elite += 20
	}
	// 计算 学生干部
	position := userResume.Position
	level := user.Level
	if position == "干事" {
		elite += 5
	} else {
		if level == "院级" {
			if position == "主席" {
				elite += 15
			} else if strings.Contains(position, "部长") {
				elite += 10
			}
		} else if level == "班级" {
			if position == "班长" || strings.Contains(position, "支书") {
				elite += 10
			}
		} else if level == "校级" {
			if strings.Contains(position, "主席") {
				elite += 20
			} else if strings.Contains(position, "部长") {
				elite += 15
			}
		}
	}

	// 没有荣誉
	if err != nil {
		user.Elite = elite
		_, err := O.Update(user, "elite")
		if err != nil {
			err = errors.New("UpdateDataFail")
		}
		return err
	}
	// 计算 荣誉
	for _, honor := range userHonors {
		honorType := honor.Type
		level := honor.Level
		if honorType == Scholarship { // 计算 奖学金
			switch level {
			case "院级":
				elite += 15
			case "校级":
				elite += 20
			case "省级":
				elite += 25
			case "国家级":
				elite += 30
			case "国际级":
				elite += 35
			}
		} else if honorType == CompetitionAwards { // 计算 赛事获奖
			switch level {
			case "院级":
				elite += 10
			case "校级":
				elite += 15
			case "省级":
				elite += 20
			case "国家级":
				elite += 25
			case "国际级":
				elite += 30
			}
		} else if honorType == Patent { // 计算 科研成果
			switch level {
			case "省级期刊":
				elite += 10
			case "国家级期刊":
				elite += 15
			case "核心期刊":
				elite += 20
			}
		} else if honorType == OtherCertificates || honorType == CertificateOfAppointment { // 计算 其他证书
			elite += 20
		}
	}

	user.Elite = elite
	_, err = O.Update(user, "elite")
	if err != nil {
		err = errors.New("UpdateDataFail")
	}
	return err
}

/*
 用户获取 指定公司岗位的 投放简历或公司更新邀请
*/
func QueryUserPutAndCompanyInvite(userId int, jobId int) (UserPutAndCompanyInvite, error) {
	var putAndInvite UserPutAndCompanyInvite

	err := O.QueryTable("user_put_and_company_invite").
		Filter("status", 1).Filter("user_id", userId).Filter("job_id", jobId).
		One(&putAndInvite)
	err = O.QueryTable("company").
		Filter("status", 1).Filter("id", putAndInvite.Company.Id).
		One(putAndInvite.Company)
	err = O.QueryTable("company_job").
		Filter("id", putAndInvite.Job.Id).Filter("status", 1).
		One(putAndInvite.Job)

	return putAndInvite, err
}

/*
 用户投放简历或公司邀请用户(单向)
*/
func InsertUserPutAndCompanyInvite(putAndInvite UserPutAndCompanyInvite) (int, error) {
	putAndInvite.Status = true
	putAndInvite.Resume = &UserResume{Id: putAndInvite.User.Id}

	id, err := O.Insert(&putAndInvite)

	return int(id), err
}

/*
 用户更新投放简历或公司更新邀请
*/
func UpdateUserPutAndCompanyInvite(putAndInvite UserPutAndCompanyInvite, field string) error {
	_, err := O.Update(
		&putAndInvite,
		field,
	)

	return err
}

/*
 用户: 查找 指定类型 用户投放/公司邀请
 若 type -1: 全部 0: 拒绝 1: 单向 2: 双向 3: offer
*/
func QueryAllUserPutAndCompanyInviteByUser(userId int, t int, page int, limit int) ([]PutAndInviteWithStar, error) {
	var putAndInvite []*UserPutAndCompanyInvite
	var err error
	var putAndInviteWithStars []PutAndInviteWithStar

	if t == -1 {
		_, err = O.QueryTable("user_put_and_company_invite").
			Filter("status", 1).Filter("user_id", userId).
			Limit(limit, page).
			All(&putAndInvite)
	} else if t == 0 {
		_, err = O.QueryTable("user_put_and_company_invite").
			Filter("status", 1).Filter("user_id", userId).Filter("offer", 0).
			Limit(limit, page).
			All(&putAndInvite)
	} else if t == 1 {
		_, _ = O.Raw("SELECT * FROM `user_put_and_company_invite` WHERE `status`=1 AND ((`user_answer`=1 AND `company_answer`=2) OR (`user_answer`=2 AND `company_answer`=1)) AND (`offer`=3 OR `offer`=2) AND `user_id`=? LIMIT ?,?", userId, page, limit).QueryRows(&putAndInvite)
	} else if t == 2 {
		_, err = O.QueryTable("user_put_and_company_invite").
			Filter("status", 1).Filter("user_id", userId).Filter("offer__gte", 2).Filter("user_answer", 1).Filter("company_answer", 1).
			Limit(limit, page).
			All(&putAndInvite)
	} else if t == 3 {
		_, err = O.QueryTable("user_put_and_company_invite").
			Filter("status", 1).Filter("user_id", userId).Filter("offer__lte", 1).
			Limit(limit, page).
			All(&putAndInvite)
	}

	for _, _putAndInvite := range putAndInvite {
		err = O.QueryTable("company").
			Filter("id", _putAndInvite.Company.Id).Filter("status", 1).
			One(_putAndInvite.Company)
		err = O.QueryTable("company_job").
			Filter("id", _putAndInvite.Job.Id).Filter("status", 1).
			One(_putAndInvite.Job)
	}

	for _, _putAndInvite := range putAndInvite {
		var putAndInviteWithStar PutAndInviteWithStar
		putAndInviteWithStar.PutAndInvite = *_putAndInvite
		putAndInviteWithStar.Star = getStar(*_putAndInvite)
		putAndInviteWithStars = append(putAndInviteWithStars, putAndInviteWithStar)
	}

	return putAndInviteWithStars, err
}

/*
util-------------------------------------util-----------------------------------util
*/

/*
 获取用户是否关注该公司
*/
func getStar(putAndInvite UserPutAndCompanyInvite) bool {
	var star UserStarCompany

	err := O.QueryTable("user_star_company").
		Filter("status", 1).Filter("user_id", putAndInvite.User.Id).Filter("company_id", putAndInvite.Company.Id).
		One(&star)

	if err != nil {
		return false
	}
	return true
}

/*
 获取一个人的所有荣誉
*/
func getAllHonor(userId int) ([]*UserHonor, error) {
	var userHonors []*UserHonor

	_, err := O.QueryTable("user_honor").
		Filter("status", 1).Filter("user_id", userId).
		All(&userHonors)

	return userHonors, err
}

/*
判断该评论是否属于该用户
*/
func checkCommentBelongUser(comment *UserComment) (result bool, err error) {
	dbComment := UserComment{Id: comment.Id}
	err = O.Read(&dbComment, "id")
	if err != nil || dbComment.CommentUser.Id != comment.CommentUser.Id {
		return false, err
	}
	return true, nil
}

/*
判断该标签是否属于该用户
*/
func checkLabelBelongUser(label *UserLabel) (result bool, err error) {
	dbLabel := UserLabel{Id: label.Id}
	err = O.Read(&dbLabel, "id")
	if err != nil || dbLabel.User.Id != label.User.Id {
		return false, err
	}
	return true, nil
}

/*
判断该简历是否属于该用户(true: 属于该用户)
*/
func checkResumeBelongUser(resume *UserResume) (result bool, err error) {
	dbResume := UserResume{Id: resume.Id}
	err = O.Read(&dbResume, "id")
	if err != nil || dbResume.User.Id != resume.User.Id {
		return false, errors.New("ResumeNotBelong")
	}
	return true, nil
}

/*
判断该标签是否已存在(已存在: true, 未存在: false)
*/
func checkLabelExist(label *UserLabel) bool {
	checkLabel := UserLabel{
		Label: label.Label,
		User:  label.User,
	}
	err := O.Read(&checkLabel, "label", "user_id")
	if err != nil {
		return false
	}
	return true
}

/*
判断用户是否为管理员
*/
func checkUserAsManager(userId int) (result bool, err error) {
	user := User{Id: userId}
	err = O.Read(&user)
	if err != nil || user.Type <= 1 {
		return false, err
	}
	return true, nil
}

/*
获取标签对应的点赞数
*/
func getPraiseNum(label *UserLabel) (int, error) {
	num, err := O.QueryTable("user_praise").
		Filter("status", 1).Filter("user_label_id", label.Id).
		Count()

	return int(num), err
}

/*
从 UserStar 获取 User
*/
func getUserFromUserStar(userStars []*UserStar) ([]*User, error) {
	var users []*User

	for _, userStar := range userStars {
		user, err := QueryUserById(userStar.User.Id)
		if err != nil {
			return nil, err
		}
		users = append(users, user)
	}

	return users, nil
}

/*
从 UserStar 获取 StarUser
*/
func getStarUserFromUserStar(userStars []*UserStar) ([]*User, error) {
	var users []*User

	for _, userStar := range userStars {
		user, err := QueryUserById(userStar.StarUser.Id)
		if err != nil {
			return nil, err
		}
		users = append(users, user)
	}

	return users, nil
}

/*
从 UserIdentity 获取 User
*/
func getUserFromUserIdentity(userIdentities []*UserIdentity) ([]*User, error) {
	var users []*User

	for _, userIdentity := range userIdentities {
		user, err := QueryUserById(userIdentity.User.Id)
		if err != nil {
			return nil, err
		}
		users = append(users, user)
	}

	return users, nil
}

/*
从 CompanyInterview 获取 Company 和 job
*/
func getCompanyAndJobFromCompanyInterview(companyInterviews []*CompanyInterview) ([]*CompanyInterview, error) {

	for _, companyInterview := range companyInterviews {
		company, err := GetCompanyById(companyInterview.Company.Id)
		if err != nil {
			return nil, err
		}
		companyInterview.Company = company
		job, err := GetCompanyJobById(companyInterview.CompanyJob.Id)
		if err != nil {
			return nil, err
		}
		companyInterview.CompanyJob = job
	}

	return companyInterviews, nil
}

/*
从用户列表中搜索符合条件的用户
*/
func searchForUserByKeyword(user *User, keyword string) bool {
	return strings.Contains(user.Nickname, keyword) ||
		strings.Contains(user.City, keyword) ||
		strings.Contains(user.Province, keyword) ||
		strings.Contains(user.Area, keyword) ||
		strings.Contains(user.RealName, keyword) ||
		strings.Contains(user.University, keyword) ||
		strings.Contains(user.Position, keyword)
}

func checkPageAndLimitOfUserStar(data []*UserStar, page int, limit int) ([]*UserStar, error) {
	if len(data) < (page)*limit {
		return nil, errors.New("PageOutOfRange")
	}
	if len(data) < (page+1)*limit {
		data = data[page*limit:]
	} else {
		data = data[page*limit : (page+1)*limit]
	}

	return data, nil
}

/*
根据关键字查询用户
*/
func getUserByKeyword(qs orm.QuerySeter, keyword string) orm.QuerySeter {
	cond := orm.NewCondition().
		Or("username__icontains", keyword).
		Or("nickname__icontains", keyword).
		Or("city__icontains", keyword).
		Or("province__icontains", keyword).
		Or("area__icontains", keyword).
		Or("real_name__icontains", keyword).
		Or("hobby1__icontains", keyword).
		Or("hobby2__icontains", keyword).
		Or("hobby3__icontains", keyword).
		Or("department__icontains", keyword).
		Or("position__icontains", keyword).
		Or("university__icontains", keyword).
		Or("email__icontains", keyword)

	qs = qs.SetCond(cond)

	return qs
}

/*
 合并用户
*/
func mergeUser(user User, dbUser *User) User {
	var returnUser User

	returnUser.Id = user.Id
	if user.Nickname == "" {
		returnUser.Nickname = dbUser.Nickname
	} else {
		returnUser.Nickname = user.Nickname
	}
	if user.RealName == "" {
		returnUser.RealName = dbUser.RealName
	} else {
		returnUser.RealName = user.RealName
	}
	if user.Gender == -1 {
		returnUser.Gender = dbUser.Gender
	} else {
		returnUser.Gender = user.Gender
	}
	if user.University == "" {
		returnUser.University = dbUser.University
	} else {
		returnUser.University = user.University
	}
	if user.Major == "" {
		returnUser.Major = dbUser.Major
	} else {
		returnUser.Major = user.Major
	}
	if user.Grade == -1 {
		returnUser.Grade = dbUser.Grade
	} else {
		returnUser.Grade = user.Grade
	}
	if user.Position == "" {
		returnUser.Position = dbUser.Position
	} else {
		returnUser.Position = user.Position
	}
	if user.Department == "" {
		returnUser.Department = dbUser.Department
	} else {
		returnUser.Department = user.Department
	}
	if user.City == "" {
		returnUser.City = dbUser.City
	} else {
		returnUser.City = user.City
	}
	if user.Area == "" {
		returnUser.Area = dbUser.Area
	} else {
		returnUser.Area = user.Area
	}
	if user.Province == "" {
		returnUser.Province = dbUser.Province
	} else {
		returnUser.Province = user.Province
	}
	if user.Avatar == "" {
		returnUser.Avatar = dbUser.Avatar
	} else {
		returnUser.Avatar = user.Avatar
	}
	if user.College == "" {
		returnUser.College = dbUser.College
	} else {
		returnUser.College = user.College
	}

	return returnUser
}
